/*
 * $Id: FudgeRoller.java 6 2009-12-09 02:11:36Z dave.terhune $
 *
 * Copyright (C) 2009 David Terhune
 *
 * This file is part of DiceRoller.
 *
 * DiceRoller is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * DiceRoller is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with DiceRoller.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.dterhune.gaming.dice;

import android.app.Activity;
import android.view.View;
import android.widget.TextView;
import java.util.Random;

/** Rolls Fudge dice. */
@SuppressWarnings("serial") // Never actually serialized, so ignore warning.
public class FudgeRoller extends Random implements View.OnClickListener
{
    /** Result text field. */
    TextView result = null;
    /** Sum text field. */
    TextView sum = null;
    
    /**
     * Creates a new FudgeRoller.
     * @param activity The parent DiceRoller
     */
    public FudgeRoller(Activity activity)
    {
        // Set the click listener
        View b = activity.findViewById(R.id.roll_1df);
        b.setOnClickListener(this);
        b = activity.findViewById(R.id.roll_4df);
        b.setOnClickListener(this);

        // Cache the text controls
        result = (TextView)activity.findViewById(R.id.fudge_result);
        sum = (TextView)activity.findViewById(R.id.fudge_sum);
    }

    /**
     * Click handler.
     * @param v view that was clicked
     */
    public void onClick(View v)
    {
        // Figure out how many dice to roll
        int dice = 0;
        switch(v.getId())
        {
            case R.id.roll_1df:
                dice = 1;
                break;

            case R.id.roll_4df:
                dice = 4;
                break;
        }

        int total = 0;
        StringBuilder sb = new StringBuilder();

        // Roll the dice
        for(int i = 0; i < dice; i++)
        {
            if(i != 0)
            {
                // Not first item; add a comma
                sb.append(", ");
            }
            switch(nextInt(3) - 1)
            {
                case -1:
                    total--;
                    sb.append("-");
                    break;
                case 0:
                    sb.append(" ");
                    break;
                case 1:
                    total++;
                    sb.append("+");
                    break;
            }
        }

        // Display the results
        String sumText = (total >= 0 ? "+" : "") + Integer.toString(total);
        result.setText(sb);
        sum.setText(sumText);
    }
}
